//
//  SHComposeView.swift
//  SHWeibo
//
//  Created by jingming wang on 16/8/4.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit
import pop

class SHComposeView: UIView {
    // 代表mainVc mainVc将该view添加为其子控件
    private var target: UIViewController?
    // 模型数组
    private lazy var composeButtonInfos: [SHComposeButtonInfo] = SHComposeButtonInfo.buttonInfos()
    // 用于保存按钮的 数组
    private lazy var buttons: [SHComposeButton] = [SHComposeButton]()
    
    // MARK: - 懒加载控件
    // 背景磨砂图片
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    // logo
    private lazy var logoImageView: UIImageView = UIImageView(imgName: "compose_slogan")
    
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: K_SCREEN_WIDTH, height: K_SCREEN_HEIGHT))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置界面
    private func setupUI() {
        addSubview(bgImageView)
        addSubview(logoImageView)
        addChildButtons()
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        logoImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
    }
    
    // MARK: - 添加按钮子控件群
    private func addChildButtons() {
        // 按钮宽高 间距
        let width: CGFloat = 80
        let height: CGFloat = 110
        let margin: CGFloat = (K_SCREEN_WIDTH - width * 3) / 4
        
        for (i, value) in composeButtonInfos.enumerate() {
            // 行数和列数
            let row = CGFloat(i/3)
            let col = CGFloat(i%3)
            // 实例化button
            let button = SHComposeButton(title: value.title ?? "", imgName: value.icon ?? "", target: self, action: "didClickButton:")
            button.frame = CGRect(x: margin+(width+margin)*col, y: (height+margin)*row+K_SCREEN_HEIGHT, width: width, height: height)
        
            // 赋值
            button.composeButtonInfo = value
            
            addSubview(button)
            // 保存按钮到数组
            buttons.append(button)
        }
    }
    
    // MARK: - 按钮点击监听
    @objc private func didClickButton(sender: SHComposeButton) {
        // 设置动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            // 遍历保存按钮的数组
            for value in self.buttons {
                // 设置透明度
                value.alpha = 0.2
                // 判断遍历到的按钮是否是当前点击的按钮
                if value == sender {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else {
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 遍历保存按钮的数组
                    for value in self.buttons {
                        value.alpha = 1
                        value.transform = CGAffineTransformIdentity
                    }
                    }, completion: { (_) -> Void in
                        guard let vcName = sender.composeButtonInfo?.nextvc else {
                            return
                        }
                        guard let projectName = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
                            return
                        }
                        // 判断class 是否为nil 而且是否可以转成UIViewController.Type
                        // 为什么 “SHComposeViewController” 因为OC中根本没有命名空间 erSwift中有命名空间
                        // 如果Swift中获取自定义类的class [项目名.类名]
                        guard let className = NSClassFromString("\(projectName).\(vcName)") as? UIViewController.Type else {
                            return
                        }
                        // 初始化
                        let tempVc = className.init()
                        let nav = UINavigationController(rootViewController: tempVc)
                        self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                            self.removeFromSuperview()
                        })
                })
                
        }
    }
    
    // MARK: - 供外界调用 跳转界面
    func showComposeView(target: UIViewController) {
        // 赋值
        self.target = target
        // 添加view
        target.view.addSubview(self)
        
        setupButtonsAnim(true)
    }
    
    // MARK: - 设置动画效果
    private func setupButtonsAnim(popUp: Bool) {
        // 间距
        let margin: CGFloat = popUp ? -350 : 350
        // 数组结合
        let set = popUp ? buttons.enumerate() : buttons.reverse().enumerate()
        // 遍历数组 分别设置动画
        for (i, value) in set {
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 设置toValue
            anim.toValue = NSValue(CGPoint:CGPoint(x: value.center.x, y: value.center.y + margin))
            // 开始时间
            anim.beginTime = CACurrentMediaTime() + Double(i)*0.025
            // 弹性系数
            anim.springBounciness = 10
            // 动画速度
            anim.springSpeed = 8
            value.pop_addAnimation(anim, forKey: nil)
        }
    }
    
    // MARK: - 点击屏幕 remove当前view
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        setupButtonsAnim(false)
        // 延迟移除当前view
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
    }

}
